package com.snow;

import com.snow.proto.my_wechat.GroupMessage;
import dbcTools.DBC_MySQL;
import io.grpc.ManagedChannel;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;

public class MyWechatServer {
    public static HashMap<Integer, HashSet<StreamObserver<GroupMessage>>> responseObserverKV;//key为group_id，value为与客户端维持的流responseObserver。

    private Server server;

    public  static Connection connection;

    private void start() throws IOException {
        DBC_MySQL dbc_mySQL = new DBC_MySQL("config.xml");
        connection = dbc_mySQL.getConnection();

        this.server = ServerBuilder.forPort(8899).addService(new MyWeChatImpl()).addService(new MyChat_Groupimpl()).build().start();
        System.out.println("server started!");

        //增加一个线程，当正常关闭jvm时关闭此服务器；当强行关闭本线程，则不会执行。
        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            System.out.println("关闭jvm");
            try {
                MyWechatServer.connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            MyWechatServer.this.stop();
        }));
    }

    private  void stop(){
        if (null != this.server){
            this.server.shutdown();
        }
    }

    //此方法是为了阻塞服务器，使其一直等待服务器的链接
    private void awaitTermination() throws InterruptedException{
        if (null != this.server){
            this.server.awaitTermination();
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {

        responseObserverKV = new HashMap<>();

        MyWechatServer server = new MyWechatServer();
        server.start();
        server.awaitTermination();
    }
}
